package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.dto.SubTaskDTO;
import com.xuedongzhilian.entity.SubTask;
import com.xuedongzhilian.service.ISubTaskService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 支线任务控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/sub-task")
public class SubTaskController {

    @Resource
    private ISubTaskService subTaskService;

    /**
     * 创建支线任务
     */
    @PostMapping
    public Result createSubTask(@RequestBody SubTaskDTO subTaskDTO) {
        SubTask subTask = new SubTask();
        BeanUtils.copyProperties(subTaskDTO, subTask);
        subTask.setUserId(UserHolder.getUser().getId());
        subTask.setStatus(1); // 未完成状态
        subTask.setCreateTime(LocalDateTime.now());
        subTask.setUpdateTime(LocalDateTime.now());
        
        boolean success = subTaskService.save(subTask);
        if (success) {
            return Result.ok(subTask);
        } else {
            return Result.fail("创建失败");
        }
    }

    /**
     * 获取用户支线任务列表
     */
    @GetMapping
    public Result getSubTasks(@RequestParam(required = false) Integer status,
                             @RequestParam(required = false) Integer type) {
        Long userId = UserHolder.getUser().getId();
        
        List<SubTask> subTasks = subTaskService.lambdaQuery()
                .eq(SubTask::getUserId, userId)
                .eq(status != null, SubTask::getStatus, status)
                .eq(type != null, SubTask::getType, type)
                .orderByDesc(SubTask::getCreateTime)
                .list();
                
        return Result.ok(subTasks);
    }

    /**
     * 完成支线任务
     */
    @PostMapping("/complete/{id}")
    public Result completeSubTask(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        SubTask subTask = subTaskService.getById(id);
        
        if (subTask == null) {
            return Result.fail("任务不存在");
        }
        
        if (!subTask.getUserId().equals(userId)) {
            return Result.fail("无权操作该任务");
        }
        
        if (subTask.getStatus() == 2) {
            return Result.fail("任务已完成");
        }
        
        subTask.setStatus(2); // 已完成状态
        subTask.setCompleteTime(LocalDateTime.now());
        subTask.setUpdateTime(LocalDateTime.now());
        
        boolean success = subTaskService.updateById(subTask);
        if (success) {
            // TODO 发放积分奖励
            return Result.ok("任务完成，奖励已发放");
        } else {
            return Result.fail("完成任务失败");
        }
    }

    /**
     * 删除支线任务
     */
    @DeleteMapping("/{id}")
    public Result deleteSubTask(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        SubTask subTask = subTaskService.getById(id);
        
        if (subTask == null) {
            return Result.fail("任务不存在");
        }
        
        if (!subTask.getUserId().equals(userId)) {
            return Result.fail("无权操作该任务");
        }
        
        boolean success = subTaskService.removeById(id);
        if (success) {
            return Result.ok("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 获取今日待完成任务
     */
    @GetMapping("/today")
    public Result getTodayTasks() {
        Long userId = UserHolder.getUser().getId();
        LocalDate today = LocalDate.now();
        
        List<SubTask> subTasks = subTaskService.lambdaQuery()
                .eq(SubTask::getUserId, userId)
                .eq(SubTask::getStatus, 1) // 未完成状态
                .le(SubTask::getDueDate, today)
                .orderByAsc(SubTask::getDueDate)
                .list();
                
        return Result.ok(subTasks);
    }
}